package com.haiyou.dc.thread.test2;

/**
 * 生产者消费者实现方式二：信号灯法
 * 设置标志位：flag来切换:表演-观看
 * 同一时间只能实现一个，表演完才能观看，观看完了才能表演
 * 实现方式：flag=true，观看wait,表演完了notify,flag=false；flag=true，表演wait,观看完了notify,,flag=true
 *
 */
public class CoTest02 {

    public static void main(String[] args) {
        Tv tv = new Tv();
        new Thread(new Play(tv)).start();
        new Thread(new Watch(tv)).start();
    }
}

//电视
class Tv {

    private String voice;
    private boolean flag = true;

    public synchronized void play(String voice) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("表演了" + voice);
        this.voice = voice;
        this.notifyAll();
        flag = !flag;
    }

    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("听到了" + voice);
        this.notifyAll();
        flag = !flag;
    }
}

//表演
class Play implements Runnable {

    private Tv tv;


    public Play(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                tv.play("奇葩说....");
            } else {
                tv.play("直播广告...");
            }
        }
    }

}

//观察
class Watch implements Runnable {

    private Tv tv;

    public Watch(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }

}
